package com.example.canvastest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class DrawingPanel extends SurfaceView implements Callback {
	PanelThread _thread;
	Paint paint;
	Rect rect;
	
	public DrawingPanel(Context context) {
		this(context, null);
	}

	
	public DrawingPanel(Context context, AttributeSet attrs) {
		super(context, attrs);

		init();
		
		getHolder().addCallback(this);
	}

	private void init() {
		paint = new Paint();
		paint.setARGB(255, 255, 0, 0);
		
		rect = new Rect();
	}

	@Override
	public void onDraw(Canvas canvas) {
		int x = -(int) (AccelerometerService.accel * 20);
		int y = (int) (AccelerometerService.accelY * 20);
		
		rect.set(canvas.getWidth()/2 - 20 + x, canvas.getHeight()/2 - 20 + y, canvas.getWidth()/2 + 20 + x, canvas.getHeight()/2 + 20 + y);
		
		canvas.drawRect(rect, paint);
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		setWillNotDraw(false); // Allows us to use invalidate() to call onDraw()

		_thread = new PanelThread(getHolder(), this); // Start the thread that
		_thread.setRunning(true); // will make calls to
		_thread.start(); // onDraw()
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		try {
			_thread.setRunning(false); // Tells thread to stop
			_thread.join(); // Removes thread from mem.
		} catch (InterruptedException e) {
		}
	}

}
